from helper import *

class geo_builder:
	def __init__(self, helper = geo_helper()):
		self.geo = ['', OP_ASK, None]
		self.helper = helper
		
	def build(self, loc, helper = None):	
		if not helper:
			helper = self.helper
		geo = self.geo
		i = 0
		while i < len(loc.info):
			name, desc, t_flag, t_op, t_geo = loc.info[i]
			t_desc, op, db = geo
			if op == OP_IGN or op == OP_SKP:
				break

			name_exists = 1
			if not name in db:
				name = helper.realname(i)
				if not name in db:
					name_exists = 0
			
			if (not name_exists and op == OP_ASK) or op == OP_AGN:
				op, name = helper.ask(i)
				if op == OP_AGN:
					if i > 0:
						i -= 1
						name, desc, flag, op, geo = loc.info[i]
						geo[1] = OP_AGN
					continue
			
			if not name_exists:
				sub = None
				if op == OP_ALL or op == OP_ASK:
					sub = dict()
				db[name] = [desc, op, sub]
			loc.info[i] = [name, desc, t_flag, op, geo]
			geo[1] = op
			geo = db[name]
			i += 1
		helper.write(i)
	
	def load(self, file, helper = None):
		count = 0
		if not helper:
			helper = self.helper
		op = helper.wizard()
		t_desc, t_op, db = self.geo
		if db:
			del db
		if op != OP_ASK and op != OP_ALL:
			op = OP_ASK
		self.geo = ['', op, dict()]
		fp = open(file, 'r')
		if fp:
			try:
				for line in fp:
					if helper.read(line):
						self.build(helper.loc, helper)
						count += 1
			finally:
				fp.close()
		return count

